import { wxUpdate } from "../../api/wxuser/index"
import { getUserInfo, setUserInfo } from "../../utils/storage"
import config from '../../config/index'

interface User {
  id: string,
  phone: string
  avatar?: string
  nickName?: string
}
Page({
  data: {
    user: {} as User,
    defaultAva: '../../static/images/defult_user.png',
    avatar: '',
    nickName: '',
    configUrl: config.BaseUrl + '/',
  },
  initData() {
    const user = getUserInfo()
    this.setData({
      user,
      nickName: user.nickName,
      avatar: user.avatar
    })
  },
  async updateUser() {
    const data: { avatar: string, nickName: string } = {
      avatar: this.data.avatar,
      nickName: this.data.nickName
    }
    const res = await wxUpdate(this.data.user.id, data)
    if(res.statusCode === config.CREATED_CODE) {
      setUserInfo(res.data)
      this.initData()
      wx.showToast({title: '保存成功', icon: 'success'})
    } else {
      wx.showToast({title: res.message, icon: 'error'})
    }
    
  },
  onChooseAvatar(e: any) {
    wx.uploadFile({
      url: this.data.configUrl + 'api/upload/image',
      filePath: e.detail.avatarUrl,
      name: 'file',
      success: (res: any) => {
        const imgRes = JSON.parse(res.data)
        this.setData({
          avatar: imgRes.data.path.replace(/\\/g, '/'),
        })
      }
    })
  },
  onShow() {
    this.initData()
  },
})